﻿/* File Created: 七月 21, 2013 */
var ComFunJS = new Object();
ComFunJS.getQueryString = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}
ComFunJS.getRootPath = function () {
    //获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
    var curWwwPath = window.document.location.href;
    //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
    var pathName = window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    //获取主机地址，如： http://localhost:8083
    var localhostPaht = curWwwPath.substring(0, pos);
    //获取带"/"的项目名，如：/uimcardprj
    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
    return (localhostPaht + projectName);
}


//将长度超过10的字符串用省略号代替
ComFunJS.convstr = function (str, len) {
    if (len) {
        return str.length > len ? str.substr(0, len) + "..." : str;
    }
    else
    {
        return str.length > 10 ? str.substr(0, 10) + "..." : str;
    }
}



//选择人员
ComFunJS.GetPeople = function (dom, checkvalue) {
    var api = frameElement.api;
    if (api) {
        MyDialog.btviewP('选择人员', 'url:Common/GetPeople.aspx?Action=GetBranchUser&checkvalue=' + checkvalue, '确认', function () {
            var people = this.content.getchecknodes();
            dom.data("people", people).val(people.username).next('input:hidden').val(people.userid);
            if (dom.is("td")) {
                dom.text(people.username);
            }
        }, 320, 430, api);
    }
    else {
        MyDialog.btview('选择人员', 'url:Common/GetPeople.aspx?Action=GetBranchUser&checkvalue=' + checkvalue, '确认', function () {
            var people = this.content.getchecknodes();
            dom.data("people", people).val(people.username).next('input:hidden').val(people.userid);
            if (dom.is("td")) {
                dom.text(people.username);
            }
        }, 320, 430);
    }



}
//选择角色代码
ComFunJS.GetBMPeople = function (dom) {
    var checkvalue = dom.next('input:hidden').val();
    if (dom.data("people")) {
        checkvalue = dom.data("people").userid;
    }
    MyDialog.btview("选择人员", 'url:../Comon/UserListN.aspx?checkvalue=' + checkvalue, '确认', function () {
        var people = this.content.getqiandaopeople();
        dom.data("people", people).val(people.username).next('input:hidden').val(people.userid);
        if (dom.is("td")) {
            dom.text(people.username);
        }
    }, 1100, 600);

}
ComFunJS.initForm = function () {
    //初始化插件（时间，选人）
    //选部门多选
    if ($(".getbranchs")[0]) {
        $(".getbranchs").each(function () {
            var dom = $(this);
            $.ajax({
                type: "GET",
                async: false,
                url: "../Comon/ComAjaxHandler.ashx",
                dataType: "html",
                data: { "Action": "GetBranchJson" },
                success: function (msg) {
                    brancharr = eval('(' + msg + ')');
                    for (var el in brancharr) {
                        var realvalue = $(".hid" + dom.attr("id")).val()
                        if (realvalue && realvalue.indexOf(el) >= 0) {
                            dom.append("<option selected='selected' value='" + el + "'>" + brancharr[el] + "</option>");
                        }
                        else {
                            dom.append("<option value='" + el + "'>" + brancharr[el] + "</option>");
                        }
                    }
                }
            });

        })
    }
    //选部门

    //时间
    //日期

    if ($(".form_date")[0]) {
        $(".form_date").datetimepicker({
            format: "yyyy-mm-dd"
        });
        $(".form_date").each(function () {
            if ($(this).val() === "") { $(this).val(ComFunJS.getnowdate("yyyy-mm-dd")); }
            $(this).trigger('change')
        })
    }


    //年份
    if ($(".form_date_year")[0]) {
        $(".form_date_year").datetimepicker({
            minView: 4,
            startView: 4,
            format: "yyyy"
        })
        if ($(".form_date_year").val() === "") { $(".form_date_year").val(ComFunJS.getnowdate("yyyy")); }
        $(".form_date_year").trigger('change')
    }

    //月份
    if ($(".form_date_mon")[0]) {
        $(".form_date_mon").datetimepicker({
            minView: 3,
            startView: 3,
            format: "yyyy-mm"
        })
        if ($(".form_date_mon").val() === "") { $(".form_date_mon").val(ComFunJS.getnowdate("yyyy-mm")); }
        $(".form_date_mon").trigger('change')
    }

    //时间
    if ($(".form_date_time")[0]) {
        $(".form_date_time").datetimepicker({
            minView: 0,
            format: "yyyy-mm-dd hh:ii"
        });
    }
    if ($(".Yan_Date")[0]) {
        $(".Yan_Date").each(function () {
            $(this).text(ComFunJS.converdate($.trim($(this).text())))
        })
    }

    //时间
    //提示插件
    if ($(".popovertip")[0]) {
        $(".popovertip").popover({
            title: '温馨提示',
            trigger: 'focus',
            placement: 'bottom'
        })
    }

    //提示插件
    try {
        //表单验证
        $("Form").validationEngine("attach", {
            autoPositionUpdate: true,
            scroll: false,
            validateNonVisibleFields: false,
            prettySelect: true,
            showOneMessage: true
        });
        //表单验证
    } catch (e) {

    }

    //搜索选择
    if ($(".YanChosen")[0]) {
        $(".YanChosen").chosen({ no_results_text: "没有找到您要查询的结果" });
    }
    //选人
    //多选

    $('.getPeoples').bind('click', function () { ComFunJS.GetBMPeople($(this)) }).attr("onfocus", "this.blur()");
    if ($(".getPeople")[0]) {
        var UserHtml = ComFunJS.getUsersHtml();
        $(".getPeople").YanSelect({
            dataobj: $(UserHtml),
            width: "300px",
            isPage: false
        });
    }
    //单选
    //选人

    //转换中文名称
    if ($(".YanUserRealName")[0]) {
        $(".YanUserRealName").each(function () {
            $(this).text(ComFunJS.convertuser($.trim($(this).text())))
        })
    }
    if ($(".YanBranchName")[0]) {
        $(".YanBranchName").each(function () {
            $(this).text(ComFunJS.convertbranch($.trim($(this).text())))
        })
    }

    if ($(".UEEDIT").length > 0) {
        var ubid = $(".UEEDIT").eq(0).attr("id");
        var um = UM.getEditor(ubid);

    }

    
    //初始化插件
}
ComFunJS.getnowdate = function (format) {
    var now = new Date();

    var year = now.getFullYear();       //年
    var month = now.getMonth() + 1;     //月
    var day = now.getDate();            //日
    var clock = year + "-";

    if (format == "yyyy-mm") {
        if (month < 10)
            clock += "0";
        clock += month + "-";
    }

    if (format == "yyyy-mm-dd") {
        if (month < 10)
            clock += "0";
        clock += month + "-";
        if (day < 10) {
            clock += "0";
        }
        clock += day + "-";
    }
    return (clock.substr(0, clock.length - 1));

}
ComFunJS.converdate = function (date) {

    var daycount = ComFunJS.daysBetween(ComFunJS.getnowdate('yyyy-mm-dd'), date);
    var datereturn = date;
    if (daycount == -1) {
        datereturn = date + "(昨天)";
    }
    if (daycount == 0) {
        datereturn = date + "(今天)";
    }
    if (daycount == 1) {
        datereturn = date + "(明天)";
    }
    if (daycount == 2) {
        datereturn = date + "(后天)";
    }
    return datereturn;
}

ComFunJS.format = function (date, str) {
    str = str.replace(/yyyy|YYYY/, date.getFullYear());
    str = str.replace(/MM/, date.getMonth() >= 9 ? ((date.getMonth() + 1) * 1).toString() : '0' + (date.getMonth() + 1) * 1);
    str = str.replace(/dd|DD/, date.getDate() > 9 ? date.getDate().toString() : '0' + date.getDate());
    return str;
}
ComFunJS.daysBetween = function (start, end) {
    var OneMonth = start.substring(5, start.lastIndexOf('-'));
    var OneDay = start.substring(start.length, start.lastIndexOf('-') + 1);
    var OneYear = start.substring(0, start.indexOf('-'));
    var TwoMonth = end.substring(5, end.lastIndexOf('-'));
    var TwoDay = end.substring(end.length, end.lastIndexOf('-') + 1);
    var TwoYear = end.substring(0, end.indexOf('-'));
    var cha = ((Date.parse(TwoMonth + '/' + TwoDay + '/' + TwoYear) - Date.parse(OneMonth + '/' + OneDay + '/' + OneYear)) / 86400000);
    return cha;
},
            //日期计算
ComFunJS.DateAdd = function (date, strInterval, Number) {
    var dtTmp = date;
    switch (strInterval) {
        case 's': return new Date(Date.parse(dtTmp) + (1000 * Number));

        case 'n': return new Date(Date.parse(dtTmp) + (60000 * Number));

        case 'h': return new Date(Date.parse(dtTmp) + (3600000 * Number));

        case 'd': return new Date(Date.parse(dtTmp) + (86400000 * Number));

        case 'w': return new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number));

        case 'q': return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number * 3, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());

        case 'm': return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());

        case 'y': return new Date((dtTmp.getFullYear() + Number), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
    }
    return date;
},

ComFunJS.StringToDate = function (DateStr) {
    var converted = Date.parse(DateStr);
    var myDate = new Date(converted);
    if (isNaN(myDate)) {
        //var delimCahar = DateStr.indexOf('/')!=-1?'/':'-';
        var arys = DateStr.split('-');
        myDate = new Date(arys[0], --arys[1], arys[2]);
    }
    return myDate;
},

ComFunJS.isconuser = function (userrealname) {
    var isConUser = false;
    for (var el in parent.usersarr) {
        if (parent.usersarr[el] === userrealname) {
            isConUser = true;
            break;
        }
    }
    return isConUser;
}

ComFunJS.print = function () {
    bdhtml = window.document.body.innerHTML;
    sprnstr = "<!--startprint-->";
    eprnstr = "<!--endprint-->";
    prnhtml = bdhtml.substr(bdhtml.indexOf(sprnstr) + 17);
    prnhtml = prnhtml.substring(0, prnhtml.indexOf(eprnstr));
    window.document.body.innerHTML = prnhtml;
    window.print();
}
/*获取可选项目信息*/
ComFunJS.getProHtml = function () {
    var ProHtml = "";
    $.ajax({
        type: "GET",
        async: false,
        url: "../Common/ComAjaxHandler.ashx",
        dataType: "html",
        data: { "Action": "GetProHtml" },
        success: function (msg) {
            ProHtml = msg;
        }
    });
    return ProHtml;
}
/*获取可选用户信息*/
ComFunJS.getUsersHtml = function () {
    var UserHtml = "";
    if ($("body").data("UserHtml")) {
        var usersarr = $("body").data("UserHtml");
        UserHtml = usersarr;
    } else {
        $.ajax({
            type: "GET",
            async: false,
            url: "../Common/ComAjaxHandler.ashx",
            dataType: "html",
            data: { "Action": "GetUserHtml" },
            success: function (msg) {
                UserHtml = msg;
            }
        });
    }
    return UserHtml;
}
ComFunJS.convertuser = function (user) {
    var returnmsg = "";
    var arruser = user.split(",");
    if (user !== "") {
        if ($("body").data("usersarr")) {
            var usersarr = $("body").data("usersarr");
            for (var i = 0; i < arruser.length; i++) {
                returnmsg = returnmsg + "," + usersarr[arruser[i]];
            }
        } else {
            $.ajax({
                type: "GET",
                async: false,
                url: ComFunJS.getRootPath() + "/Comon/ComAjaxHandler.ashx",
                dataType: "html",
                data: { "Action": "GetUserJson" },
                success: function (msg) {
                    usersarr = eval('(' + msg + ')');
                    for (var i = 0; i < arruser.length; i++) {
                        returnmsg = returnmsg + "," + usersarr[arruser[i]]
                    }
                    $("body").data("usersarr", usersarr);
                }
            });
        }
    }
    if (returnmsg.length > 1) {
        returnmsg = returnmsg.substring(1);
    }
    return returnmsg;
}

ComFunJS.convertbranch = function (branch) {
    var returnmsg = branch;
    if ($("body").data("brancharr")) {
        var brancharr = $("body").data("brancharr");
        returnmsg = brancharr[branch];
    } else {
        $.ajax({
            type: "GET",
            async: false,
            url: ComFunJS.getRootPath() + "/Comon/ComAjaxHandler.ashx",
            dataType: "html",
            data: { "Action": "GetBranchJson" },
            success: function (msg) {
                brancharr = eval('(' + msg + ')');
                returnmsg = brancharr[branch];
                $("body").data("brancharr", brancharr);
            }
        });
    }
    return returnmsg;
}

ComFunJS.getsjs = function () {
    var returnnum = 0;
    var count = 1000;
    var original = new Array;//原始数组
    //给原始数组original赋值
    for (var i = 0; i < count; i++) {
        original[i] = i + 1;
    }
    for (var num, i = 0; i < count; i++) {
        do {
            num = Math.floor(Math.random() * count);
            returnnum = original[num];
        } while (original[num] == null);
        original[num] = null;
    }
    return returnnum;
}
ComFunJS.hbtable = function (table, conindex) {
    var j = 0;
    var firstdata = "";
    $("tbody tr", table).each(function (i) {
        var data = $.trim($(this).children().eq(conindex).text());
        if (i != 0) {
            if ((data != "" && data != firstdata) || i == $("tbody tr", table).length - 1) {
                var td = $("tbody tr", table).eq(i - j).children().eq(conindex)
                if (i == $("tbody tr", table).length - 1) {
                    $(this).children().eq(conindex).css("display", "none");
                    td.attr("rowspan", j + 1);
                } else {
                    td.attr("rowspan", j);
                    j = 1;
                    firstdata = data;
                }
                td.css({ "text-align": "center", "vertical-align": "middle" });
            } else {
                j++;
                $(this).children().eq(conindex).css("display", "none");

            }
        } else {
            j++;
            firstdata = data;
        }
    })
}

ComFunJS.DateMethod = {
    //格式化日期
    format: function (date, str) {
        str = str.replace(/yyyy|YYYY/, date.getFullYear());
        str = str.replace(/MM/, date.getMonth() >= 9 ? ((date.getMonth() + 1) * 1).toString() : '0' + (date.getMonth() + 1) * 1);
        str = str.replace(/dd|DD/, date.getDate() > 9 ? date.getDate().toString() : '0' + date.getDate());
        return str;
    },
    //两个日期间的天数,-数为小于，正数为大于
    daysBetween: function (start, end) {
        var OneMonth = start.substring(5, start.lastIndexOf('-'));
        var OneDay = start.substring(start.length, start.lastIndexOf('-') + 1);
        var OneYear = start.substring(0, start.indexOf('-'));
        var TwoMonth = end.substring(5, end.lastIndexOf('-'));
        var TwoDay = end.substring(end.length, end.lastIndexOf('-') + 1);
        var TwoYear = end.substring(0, end.indexOf('-'));
        var cha = ((Date.parse(TwoMonth + '/' + TwoDay + '/' + TwoYear) - Date.parse(OneMonth + '/' + OneDay + '/' + OneYear)) / 86400000);
        return cha;
    },
    //判断是否周末
    isWeekend: function (date) {
        return date.getDay() % 6 === 0;
    },

    //判断是否周一
    isWeekstr: function (date) {
        return date.getDay() === 1;
    },
    //日期计算
    DateAdd: function (date, strInterval, Number) {
        var dtTmp = date;
        switch (strInterval) {
            case 's': return new Date(Date.parse(dtTmp) + (1000 * Number));

            case 'n': return new Date(Date.parse(dtTmp) + (60000 * Number));

            case 'h': return new Date(Date.parse(dtTmp) + (3600000 * Number));

            case 'd': return new Date(Date.parse(dtTmp) + (86400000 * Number));

            case 'w': return new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number));

            case 'q': return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number * 3, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());

            case 'm': return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());

            case 'y': return new Date((dtTmp.getFullYear() + Number), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
        }
        return date;
    },
    getMonths: function (start, end) {
        start = Date.parse(start); end = Date.parse(end);
        var months = [];
        months[start.getMonth()] = [start];
        var last = start;
        while (last.compareTo(end) === -1) {
            var next = last.clone().addDays(1);
            if (!months[next.getMonth()]) { months[next.getMonth()] = []; }
            months[next.getMonth()].push(next);
            last = next;
        }
        return months;
    },
    getDays: function (year, month) {
        var days = 30;
        if (month === "02")
            days = 28;
        if ((",01,03,05,07,08,10,12,").indexOf("," + month + ",") > -1)
            days = 31;
        if (month == "02" && parseInt(year) % 4 === 0 && !(parseInt(year) % 100 === 0 && !(parseInt(year) % 400 === 0)))
            days = 29;
        return days;
    },
    StringToDate: function (DateStr) {
        var converted = Date.parse(DateStr);
        var myDate = new Date(converted);
        if (isNaN(myDate)) {
            //var delimCahar = DateStr.indexOf('/')!=-1?'/':'-';
            var arys = DateStr.split('-');
            myDate = new Date(arys[0], --arys[1], arys[2]);
        }
        return myDate;
    },
    //获取日期为某年的第几周
    GetWeekIndex: function (datestr) {
        var dateobj = this.StringToDate(datestr);
        var firstDay = this.GetFirstWeekBegDay(dateobj.getFullYear());
        if (dateobj < firstDay) {
            firstDay = this.GetFirstWeekBegDay(dateobj.getFullYear() - 1);
        }
        d = Math.floor((dateobj.valueOf() - firstDay.valueOf()) / 86400000);
        return Math.floor(d / 7) + 1;
    },
    //获取某年的第一天
    GetFirstWeekBegDay: function (year) {
        var tempdate = new Date(year, 0, 1);
        var temp = tempdate.getDay();
        if (temp === 1) {
            return tempdate;
        }
        temp = temp === 0 ? 7 : temp;
        tempdate = tempdate.setDate(tempdate.getDate() + (8 - temp));
        return new Date(tempdate);
    }
};

